package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.enums.BizEnum;
import com.qk.common.exception.BizException;
import com.qk.management.annotation.DataSyncAnnotation;
import com.qk.management.annotation.RedisCacheAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @Author:gzc
 * @Date: 2025/10/17 12:38
 * @Description:
 */
@Slf4j
@Component
@Aspect
public class RedisCacheAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Around("@annotation(com.qk.management.annotation.RedisCacheAnnotation)")
    public Object redisAdvice(ProceedingJoinPoint joinPoint) {
        Object result = null;
        String redisKey = null;
        long expire = 0;
        TimeUnit expireTimeUnit = null;
        try {
            Class<?> targetClass = joinPoint.getTarget().getClass();
            String methodName = joinPoint.getSignature().getName();
            Method method = targetClass.getMethod(methodName);
            RedisCacheAnnotation annotation = method.getAnnotation(RedisCacheAnnotation.class);
            String key = annotation.key();
            if (!ObjectUtil.isEmpty(key)) {
                redisKey = key;
            } else {
                redisKey = annotation.keyPrefix() + methodName;
            }
            expire = annotation.expire();
            expireTimeUnit = annotation.expireTimeUnit();
            String jsonStr = redisTemplate.opsForValue().get(redisKey);
            if (ObjectUtil.isNotEmpty(jsonStr)) {
                log.info("查询redis缓存中的数据");
                return JSONUtil.toBean(jsonStr, method.getReturnType());
            }
        } catch (Exception e) {
            log.error("查询redis缓存中的数据异常: {}", e.getMessage());
        }
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            log.info("查询数据库中的数据异常:{}", e.getMessage());
            BizException.throwBizException(BizEnum.GENERATE_ERROR);
        }
        try {
            redisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(result), expire, expireTimeUnit);
        } catch (Exception e) {
            log.error("缓存数据异常: {}", e.getMessage());
        }
        return result;
    }

    @AfterReturning(value = "@annotation(com.qk.management.annotation.DataSyncAnnotation)",
    returning = "result")
    public void dataSyncAdvice(JoinPoint joinPoint, Object result) {
        try {
            Class<?> targetClass = joinPoint.getTarget().getClass();
            String methodName = joinPoint.getSignature().getName();
            Method method = targetClass.getMethod(methodName);
            DataSyncAnnotation annotation = method.getAnnotation(DataSyncAnnotation.class);
            String key = annotation.key();
            String keyPrefix = annotation.keyPrefix();
            long expire = annotation.expire();
            TimeUnit expireTimeUnit = annotation.expireTimeUnit();
            String redisKey;
            if (!ObjectUtil.isEmpty(key)) {
                redisKey = key;
            } else {
                redisKey = keyPrefix + methodName;
            }
            redisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(result), expire, expireTimeUnit);
        } catch (Exception e) {
            log.error("同步缓存异常: {}", e.getMessage());
        }
    }

}
